﻿using Microsoft.Win32;
using System;
using System.Collections.ObjectModel;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;

namespace GenUI.WPF.GenControls
{
    public class GenLog : Control
    {
        readonly object _lock = new object();
        private static ObservableCollection<Log> Logs { get; set; } = new ObservableCollection<Log>();
        public string LogPath { get; set; } = $"D:\\Logs";
        public bool OnlyShow { get; set; } = false;
        ListView _Lv;
        Button _btnNowLog;
        Button _btnLogPath;
        RowDefinition _rdDown;
        public int MaxCount
        {
            get => (int)GetValue(MaxCountProperty);
            set => SetValue(MaxCountProperty, value);
        }
        public static readonly DependencyProperty MaxCountProperty =
               DependencyProperty.Register("MaxCount", typeof(int), typeof(GenLog), new PropertyMetadata(50));
        public string Title
        {
            get => (string)GetValue(TitleProperty);
            set => SetValue(TitleProperty, value);
        }
        public static readonly DependencyProperty TitleProperty =
               DependencyProperty.Register("Title", typeof(string), typeof(GenLog), new PropertyMetadata("DefaultTitle"));

        static GenLog()
        {
            DefaultStyleKeyProperty.OverrideMetadata(typeof(GenLog), new FrameworkPropertyMetadata(typeof(GenLog)));
        }
        public void TipsLog(string logMsg) => Add(logMsg, LogLevel.Tips, true);
        public void ImportantLog(string logMsg) => Add(logMsg, LogLevel.Important, true);
        public void ErrorLog(string logMsg) => Add(logMsg, LogLevel.Error, true);
        public void DebugLog(string logMsg) => Add(logMsg, LogLevel.Debug, true);
        public void Add(string logMsg, LogLevel logLevel, bool isShow)
        {
            try
            {
                Log log = new Log(logMsg, logLevel);
                if (isShow)
                {
                    this.Dispatcher.BeginInvoke(new Action(() =>
                    {
                        if (_Lv?.IsMouseOver == false)
                            Logs.Add(log);
                        if (Logs.Count > MaxCount && Logs.Count > 50)
                            Logs.RemoveAt(0);
                        if (_Lv != null && !_Lv.IsMouseOver)
                            _Lv.ScrollIntoView(log);
                    }));
                }
                if (!OnlyShow)
                {
                    lock (_lock)
                    {
                        string path = $"{LogPath}\\{DateTime.Now:yyyyMMdd}\\";
                        Directory.CreateDirectory(path);
                        path += $"Log_{DateTime.Now:HH}.txt";
                        File.AppendAllText(path, log.ShowLog + "\r\n", Encoding.UTF8);
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
        }
        public override void OnApplyTemplate()
        {
            base.OnApplyTemplate();
            _Lv = GetTemplateChild("PART_lv") as ListView;
            _btnNowLog = GetTemplateChild("PART_btnNowLog") as Button;
            _btnLogPath = GetTemplateChild("PART_btnLogPath") as Button;
            _rdDown = GetTemplateChild("PART_rdDown") as RowDefinition;
            _Lv.ItemsSource = Logs;
            _btnNowLog.Click += BtnNowLog_Click;
            _btnLogPath.Click += BtnLogPath_Click;
        }
        private void BtnLogPath_Click(object sender, RoutedEventArgs e)
        {
            OpenFileDialog logsPath = new OpenFileDialog()
            {
                InitialDirectory = $"{LogPath}\\{DateTime.Now:yyyyMMdd}\\",
                Multiselect = false,
            };
            if (logsPath.ShowDialog() == true)
                System.Diagnostics.Process.Start(logsPath.FileName);
        }
        private void BtnNowLog_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                System.Diagnostics.Process.Start($"{LogPath}\\{DateTime.Now:yyyyMMdd}\\Log_{DateTime.Now:HH}.txt");
            }
            catch (Exception)
            {
                MessageBox.Show("暂无日志信息！");
            }
        }
    }
}
